<?php

namespace addons\facrm\library\notice\engine;

use app\admin\model\Admin;
use fast\Http;
use think\Exception;
use think\Queue;

/**
 * 公众号通知
 * @author amplam 122795200@qq.com
 * @Date   2021年8月18日
 */
class Mp extends Server
{


    /**
     * 构造方法
     * Mp constructor.
     * @param $config
     */
    public function __construct($config = array())
    {
        $this->config = $config;
    }

    /**
     * 发送通知
     * @param $config
     * @param $data
     * @param array $replace_data
     * @return bool
     */
    public function send($config, $data, $replace_data = array())
    {
        $platform = 'admin_mp';//微信公众号
        //判断是否安装了第三方登录
        $third = get_addon_info('third');
        if (!$third || $third['state'] != 1) {
            $this->error ="没安装第三方登录插件";
            return false;
        }
        //获取openids
        $thirdModel = new \addons\third\model\Third();
        $openids = $thirdModel->where('platform', $platform)->where('user_id', 'in', $data['admin_ids'])->column('openid');
        if (!$openids){
            $this->error ="没有绑定微信公众号";
            return false;
        }

        $tpl = $config->values['content'];
        $tpl = is_array($tpl) ? $tpl : (array)json_decode($tpl, true);
        foreach ($tpl as $item) {

            $value = str_replace('.DATA}}', '', str_replace('{{', '', $item['value']));

            if ($value) {
                $data_temp[$value] = [
                    'value' => ($item['key'] != 'diy_text') ?
                        ($item['def_val'] ? $item['def_val'] :
                            (isset($replace_data[$item['key']]) ? $replace_data[$item['key']] : ''))
                        : $item['def_val']
                ];
            }
        }

        $t_config = get_addon_config('third');
        try {
            $app = \EasyWeChat\Factory::officialAccount([
                'app_id' => $t_config['wechat']['app_id'],
                'secret' => $t_config['wechat']['app_secret'],
                'response_type' => 'array',
            ]);
        } catch (\Exception $e) {
            $this->error .= $e->getMessage();
            return false;
        }

        //发送模板消息
        foreach ($openids as $openid) {
            try {
                $send_data=[
                    'touser' => $openid,
                    'template_id' => $config->values['tpl_id'],
                    'url' => isset($config->values['url']) ? $config->values['url'] : '',
                    'data' => $data_temp,
                ];
                $res = $app->template_message->send($send_data);
                \addons\facrm\model\Notices::add($send_data,"Mp",$res['errcode']==0?1:'0',$res['errmsg']);

            } catch (\Exception $e) {
                $this->error .= $e->getMessage();
                return  false;
            }

        }
    }
}